<?php

namespace common\models\folder;

use Yii;
use common\models\user\UserBranch;
use common\models\wechat\WechatUser;
use common\models\user\UserAccount;
use common\helpers\Utils;

/**
 * This is the model class for table "{{%member}}".
 *
 * @property int $id
 * @property string $user_id 用户ID
 * @property string $type 会员类型
 * @property string $qrcode_ticket 会员类型
 * @property string $level 等级
 * @property string $expired_at 会员失效时间
 * @property int $status 会员状态：-1取消，0未支付，1已支付
 * @property string $created_at 创建时间
 * @property string $updated_at 更新时间
 */
class Member extends \common\db\ActiveRecord {

    use \common\traits\Constants;
    use \common\traits\User;

    CONST STATUS_DEFAULT = 0;
    CONST STATUS_ACTIVED = 10;
    CONST STATUS_FORBID = -1;

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return '{{%member}}';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['user_id', 'type_id', 'expired_at', 'status', 'created_at', 'updated_at', 'deleted_at'], 'integer'],
            [['secret', 'auth_token', 'qrcode_ticket'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'user_id' => '用户ID',
            'type_id' => '会员类型',
            'level' => '等级',
            'expired_at' => '会员失效时间',
            'status' => '状态',
            'secret' => '机密Key',
            'auth_token' => '授权令牌',
            'qrcode_ticket' => '二维码素材Ticket',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
            'deleted_at' => '删除时间',
            //
            'downersCount' => '下线数',
        ];
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey() {
        $this->secret = Yii::$app->security->generateRandomString(32);
        $this->auth_token = Yii::$app->security->generateRandomString();
    }

    public static function findPyramiderByUserId($userid) {
        $model = static::find()->where([
            'user_id' => $userid,
            'status' => self::STATUS_ACTIVED,
            'deleted_at' => 0,
        ])
        ->andWhere(['>', 'expired_at', time()])
        ->andWhere(['!=', 'type_id', 0])
        ->one();
        if (!$model) {
            $brancher = UserBranch::findOne(['user_id' => $userid]);
            if ($brancher) {
                return $brancher->getUpper()->active()->all();
            }
        }
        return $model;
    }

    public function getBranchs() {
        return $this->hasMany(UserBranch::className(), ['member_id' => 'id'])->andWhere([
            'status' => UserBranch::STATUS_ACTIVED,
            'deleted_at' => 0,
        ]);
    }

    /**
     * 获取会员分支
     * @return type
     */
    public function getUpper() {
        if ($this->memebr) {
            return $this->memebr->upper;
        }
        return null;
    }

    public function getDownersCount() {
        return $this->getBranchs()->count();
    }

    public function getData() {
        return $this->hasOne(MemberData::className(), ['user_id' => 'user_id']);
    }

    public function getWechatUser() {
        return $this->hasOne(WechatUser::className(), ['user_id' => 'user_id']);
    }

    public function getAccount() {
        return $this->hasOne(MemberAccount::className(), ['member_id' => 'id']);
    }

    public function getType() {
        return $this->hasOne(MemberType::className(), ['id' => 'type_id']);
    }

    public function getLevel() {
        if ($this->type) {
            return $this->type->toArray();
        }
        return [
            'level' => 0,
            'name' => '总店',
            'description' => '总店',
            'scale' => 0,
            'recharge' => 0,
        ];
    }

    /**
     * Renders the index view for the module
     * @return string
     */
    public function getQrcode() {
        $ticket = null;
        $qrcode = null;
        $root = Yii::getAlias('@uploads');
        $savefile = null;
        $path = '/member/qrcode/';
        Utils::dirCreate($root . $path);
        $filename = $this->id . '.jpg';
        $savefile = $path . $filename;

        if (file_exists($root . $savefile)) {
            return Utils::cdn($savefile);
        }
        if ($this->qrcode_ticket) {
            $ticket = $this->qrcode_ticket;
        }
        $wechat = Yii::$app->wechat;
        if ($ticket == null) {
            $data = [
                'action_name' => 'QR_LIMIT_STR_SCENE',
                'action_info' => [
                    'scene' => [
                        'scene_id' => 1,
                        'scene_str' => 'member_' . $this->id,
                    ]
                ]
            ];
            $ticket = $wechat->createQrCode($data);
        }
        if ($ticket && isset($ticket['ticket'])) {
            $qrcode = Yii::$app->wechat->getQrCode($ticket['ticket']);
        }
        if ($qrcode) {
            copy($qrcode, $root . $savefile);
            return Utils::cdn($savefile);
        }

        return '';
    }

}
